package com.liwei.lwmail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liwei.common.utils.HttpUtils;
import com.liwei.lwmail.member.dao.MemberLevelDao;
import com.liwei.lwmail.member.entity.MemberLevelEntity;
import com.liwei.lwmail.member.exception.PhoneNumberExistException;
import com.liwei.lwmail.member.exception.UsernameExistException;
import com.liwei.lwmail.member.vo.MemberLoginVo;
import com.liwei.lwmail.member.vo.MemberRegisterVo;
import com.liwei.lwmail.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.common.utils.PageUtils;
import com.liwei.common.utils.Query;

import com.liwei.lwmail.member.dao.MemberDao;
import com.liwei.lwmail.member.entity.MemberEntity;
import com.liwei.lwmail.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao levelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo member) {
        MemberEntity memberEntity = new MemberEntity();

        //检查用户名和手机号是否唯一
        checkUsernameUnique(member.getUsername());
        checkPhoneNumberUnique(member.getPhoneNumber());

        memberEntity.setUsername(member.getUsername());
        memberEntity.setNickname(member.getUsername());
        memberEntity.setMobile(member.getPhoneNumber());

        //密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(member.getPassword());
        memberEntity.setPassword(encode);

        MemberLevelEntity levelEntity = levelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0){
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkPhoneNumberUnique(String phoneNumber) throws PhoneNumberExistException{
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phoneNumber));
        if (count > 0){
            throw new PhoneNumberExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String username = vo.getUsername();
        String password = vo.getPassword();
        //1、数据库查询用户信息
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", username)
                                                                                        .or().eq("mobile", username));
        if (entity == null){
            //登陆失败
            return null;
        }
        //2、获取数据库的password
        String entityPassword = entity.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //3、密码匹配
        boolean matches = encoder.matches(password, entityPassword);
        if (matches){
            //登陆成功
            return entity;
        }else {
            return null;
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        String accessToken = socialUser.getAccess_token();
        String expiresIn = socialUser.getExpires_in() + "";
        //判断当前社交用户是否已经注册过
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (entity != null){
            //该用户已经注册过,更新令牌和过期时间
            MemberEntity memberEntity = new MemberEntity();
            BeanUtils.copyProperties(entity,memberEntity);
            memberEntity.setAccessToken(accessToken);
            memberEntity.setExpiresIn(expiresIn);

            baseMapper.updateById(memberEntity);
            return memberEntity;
        }else {
            //进行注册
            MemberEntity registerEntity = new MemberEntity();
            try {
                //查询当前社交帐号的基本信息
                /*
                GET https://api.weibo.com/2/users/show.json
                 请求参数          必选 	     类型及范围 	说明
                access_token 	true 	    string 	    采用OAuth授权方式为必填参数，OAuth授权后获得。
                uid 	        false 	    int64 	    需要查询的用户ID。
                screen_name 	false 	    string 	    需要查询的用户昵称。参数uid与screen_name二者必选其一，且只能选其一；
                */
                Map<String, String> headers = new HashMap<>();
                Map<String, String> querys = new HashMap<>();
                querys.put("access_token",accessToken);
                querys.put("uid",uid);

                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", headers, querys);
                if (response.getStatusLine().getStatusCode() == 200){
                    //查询成功
                    String jsonStr = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    //获取社交帐号信息
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");

                    //设置用户信息
                    registerEntity.setNickname(name);
                    registerEntity.setGender(gender.equals("m")?1:0);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            //.....其他信息
            registerEntity.setSocialUid(uid);
            registerEntity.setAccessToken(accessToken);
            registerEntity.setExpiresIn(expiresIn);
            baseMapper.insert(registerEntity);
            return registerEntity;
        }
    }

}